package com.iwhalecloud.bss.kite.cucc.service.flow;

import com.alibaba.fastjson.JSONObject;
import com.iwhalecloud.bss.kite.cart.common.constant.KiteCartSymbolConsts;
import com.iwhalecloud.bss.kite.cart.common.util.KiteCartListUtils;
import com.iwhalecloud.bss.kite.cart.common.util.KiteCartStringUtils;
import com.iwhalecloud.bss.kite.client.dto.flow.KitePageDefineDTO;
import com.iwhalecloud.bss.kite.common.constant.KeyConsts;
import com.iwhalecloud.bss.kite.common.constant.KeyConsts3;
import com.iwhalecloud.bss.kite.common.util.JsonUtils;
import com.iwhalecloud.bss.kite.common.util.KiteBeanUtils;
import com.iwhalecloud.bss.kite.common.util.KiteListUtils;
import com.iwhalecloud.bss.kite.common.util.KiteMapUtils;
import com.iwhalecloud.bss.kite.common.util.KiteStringUtils;
import com.iwhalecloud.bss.kite.cucc.client.api.flow.IPageFlowDefinitionService;
import com.iwhalecloud.bss.kite.cucc.client.dto.flow.PageFlowDefinitionDTO;
import com.iwhalecloud.bss.kite.cucc.client.dto.flow.PageNavigationDTO;
import com.iwhalecloud.bss.kite.cucc.dataservice.entity.lcdp.BusiObject;
import com.iwhalecloud.bss.kite.cucc.dataservice.entity.lcdp.PageFlowConditionConfig;
import com.iwhalecloud.bss.kite.cucc.dataservice.entity.lcdp.PageFlowDefinition;
import com.iwhalecloud.bss.kite.cucc.dataservice.entity.lcdp.PageTraceDTO;
import com.iwhalecloud.bss.kite.cucc.dataservice.mapper.lcdp.BusiObjectMapper;
import com.iwhalecloud.bss.kite.cucc.dataservice.mapper.lcdp.PageFlowDefinitionMapper;
import com.iwhalecloud.bss.kite.cucc.dataservice.mapper.lcdp.PageTraceMapper;
import com.iwhalecloud.bss.kite.dataservice.cache.DcSystemParamCache;
import com.ztesoft.bss.base.staticdata.CoreDataPublic;
import com.ztesoft.bss.common.util.SpringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

@Service
public class PageFlowDefinitionService implements IPageFlowDefinitionService {

    @Autowired
    private PageFlowDefinitionMapper pageFlowDefinitionMapper;

    @Autowired
    private PageTraceMapper pageTraceMapper;

    @Autowired
    private BusiObjectMapper busiObjectMapper;

    @Override
    public PageFlowDefinitionDTO getPageFlowDefinition(String serviceOfferId, String cateId, String objId, String tacheCode) {
        // 查询出所有的页面流
        Example example = new Example(PageFlowDefinition.class);
        example.createCriteria().andEqualTo("statusCd", "00A");
        List<PageFlowDefinition> pageFlowDefinitionList = pageFlowDefinitionMapper.selectByExample(example);

        return this.filterPageFlowDefinition(pageFlowDefinitionList, serviceOfferId, cateId, objId, tacheCode);
    }

    @Override
    public PageFlowDefinitionDTO getPageFlowDefinitionNew(String serviceOfferId, String cateId, String objId, String tacheCode) {
        // 查询出所有的页面流
        Example example = new Example(PageFlowDefinition.class);
        example.createCriteria().andEqualTo("statusCd", "00A").andEqualTo("conditionExpress", KiteCartStringUtils.joinWith(KiteCartSymbolConsts.UNDERLINE, serviceOfferId, cateId));
        List<PageFlowDefinition> pageFlowDefinitionList = pageFlowDefinitionMapper.selectByExample(example);

        return this.filterPageFlowDefinition(pageFlowDefinitionList, serviceOfferId, cateId, objId, tacheCode);
    }

    private PageFlowDefinitionDTO filterPageFlowDefinition(List<PageFlowDefinition> pageFlowDefinitionList, String serviceOfferId, String cateId, String objId, String tacheCode) {
        if (KiteListUtils.isEmpty(pageFlowDefinitionList)) {
            return null;
        }
        List<String> jsonList = pageFlowDefinitionList.stream().map(PageFlowDefinition::getConditionConfigJson)
            .collect(Collectors.toList());
        String targetStream = jsonList.stream().filter(json -> {
            List<PageFlowConditionConfig> list = JsonUtils.parseArray(json, PageFlowConditionConfig.class);
            if (KiteListUtils.isNotEmpty(list)) {
                PageFlowConditionConfig serviceOfferCondition = list.stream().
                    filter(conditionConfig -> KiteStringUtils.equals(conditionConfig.getAttrValueCode(), KeyConsts3.SERVICE_ACTION)).findFirst()
                    .orElse(new PageFlowConditionConfig());
                PageFlowConditionConfig cateIdCondition = list.stream().
                    filter(conditionConfig -> KiteStringUtils.equals(conditionConfig.getAttrValueCode(), KeyConsts3.GOODS_CATEGORY)).findFirst()
                    .orElse(new PageFlowConditionConfig());
                PageFlowConditionConfig goodsSkuCondition = list.stream().
                    filter(conditionConfig -> KiteStringUtils.equals(conditionConfig.getAttrValueCode(), KeyConsts3.SERVICE_PRODUCT)).findFirst()
                    .orElse(null);
                // 判断tacheCode是否为空
                if (KiteStringUtils.isEmpty(tacheCode) || KiteStringUtils.equals(tacheCode, KeyConsts3.ORDER_INPUT)) {
                    // 若为空或者为OrderInput，则可能是订单录入,继续判断ServiceOfferId和CateId
                    if (KiteStringUtils.equals(serviceOfferCondition.getValue(), serviceOfferId)
                        && KiteStringUtils.equals(cateIdCondition.getValue(), cateId)) {
                        /**
                         * 默认匹配信息录入页面流
                         * IDC配置了预销户和预销户止租，进入预销户页面时，找到的是预销户止租的页面流，如果入参没有传环节编码，默认匹配信息录入页面流  start
                         */
                        PageFlowConditionConfig tacheCodeCondition = list.stream().
                            filter(conditionConfig -> KiteStringUtils.equals(conditionConfig.getAttrValueCode(), KeyConsts3.PROC_UNIT)).findFirst()
                            .orElse(null);
                        if( tacheCodeCondition!=null&&!KiteStringUtils.equals(tacheCodeCondition.getValue(), "")&&!KiteStringUtils.equals(tacheCodeCondition.getValue(),KeyConsts3.ORDER_INPUT) ){
                            return false;
                        }
                        //IDC配置了预销户和预销户止租，进入预销户页面时，找到的是预销户止租的页面流，如果入参没有传环节编码，默认匹配信息录入页面流  end

                        if (goodsSkuCondition == null) {
                            return true;
                        }
                        else {
                            String busiObjectCode = goodsSkuCondition.getValue();
                            BusiObject busiObject = getValidBusiObject(busiObjectCode);
                            if (!Objects.isNull(busiObject)) {
                                String extSystemCode = busiObject.getExtSystemCode();
                                if (KiteStringUtils.isNotEmpty(extSystemCode)) {
                                    return KiteStringUtils.equals(extSystemCode, objId);
                                }
                                else {
                                    return KiteStringUtils.equals(goodsSkuCondition.getValue(), objId);
                                }
                            }
                        }
                    }
                }
                else {
                    // tache不为空且不等于OrderInput
                    PageFlowConditionConfig tacheCodeCondition = list.stream().
                        filter(conditionConfig -> KiteStringUtils.equals(conditionConfig.getAttrValueCode(), KeyConsts3.PROC_UNIT)).findFirst()
                        .orElse(new PageFlowConditionConfig());
                    if (KiteStringUtils.equals(serviceOfferCondition.getValue(), serviceOfferId)
                        && KiteStringUtils.equals(cateIdCondition.getValue(), cateId)
                        && KiteStringUtils.equals(tacheCodeCondition.getValue(), tacheCode)) {
                        return true;
                    }
                }
            }
            return false;
        }).findFirst().orElse(null);
        //通过目标流找到对应的页面ID
        PageFlowDefinition flowDefinition = pageFlowDefinitionList.stream()
            .filter(pageFlowDefinition -> Objects.nonNull(targetStream) && KiteStringUtils.equals(pageFlowDefinition.getConditionConfigJson(), targetStream))
            .findFirst().orElse(null);
        return KiteBeanUtils.transform(flowDefinition, PageFlowDefinitionDTO.class);
    }

    @Override
    public PageNavigationDTO transferLcdpPageNavigation(String serviceOfferId, String objId, String offerType, String tacheCode, PageFlowDefinitionDTO flowDefinition) {
        PageNavigationDTO pageNavigationDTO = new PageNavigationDTO();
        String pageFlowId = String.valueOf(flowDefinition.getPageFlowId());
        pageNavigationDTO.setServiceOfferId(serviceOfferId);
        pageNavigationDTO.setNavigationId(pageFlowId);
        pageNavigationDTO.setName(flowDefinition.getFlowName());
        pageNavigationDTO.setTemplateId("1");
        //查询出所有的页面环节
        List<PageTraceDTO> pageTraceList = pageTraceMapper.selectAllPageStep(pageFlowId);
        //根据pageFlowId和traceId查询横向页面流
        if (KiteListUtils.isNotEmpty(pageTraceList)) {
            List<PageTraceDTO> pageTraceListExt = pageTraceMapper.selectAllTrace(pageFlowId);
            //将页面环节和页面实例信息整合
            pageTraceList = mergePageTraceDTO(pageTraceList, pageTraceListExt);
            List<KitePageDefineDTO> kitePageDefines = new ArrayList<>();
            boolean isExist = true;
            for (PageTraceDTO pageTraceDTO : pageTraceList) {
                // 判断是否是当前singleGoodsSku
                String conditionConfigJson = pageTraceDTO.getConditionConfigJson();
                List<Map> conditionList = JSONObject.parseArray(conditionConfigJson, Map.class);
                if (KiteListUtils.isNotEmpty(conditionList)) {
                    Map<String, Object> conditionMap = conditionList.get(0);
                    String attrValueCode = KiteMapUtils.getString(conditionMap, "attrValueCode");
                    if (KiteStringUtils.isNotEmpty(attrValueCode)
                        && KiteStringUtils.equals(attrValueCode, "PAGE_FLOW_SCENE_2000")) {
                        String busiObjectCode = KiteMapUtils.getString(conditionMap, "value");
                        if (KiteStringUtils.isNotEmpty(busiObjectCode)) {
                            Example busiObjectExample = new Example(BusiObject.class);
                            busiObjectExample.createCriteria().andEqualTo("busiObjectCode", busiObjectCode)
                                .andEqualTo("statusCd", "00A");
                            List<BusiObject> busiObjectList = busiObjectMapper.selectByExample(busiObjectExample);
                            if (KiteListUtils.isNotEmpty(busiObjectList)) {
                                BusiObject busiObject = busiObjectList.get(0);
                                String extSystemCode = busiObject.getExtSystemCode();
                                if (KiteStringUtils.isNotEmpty(extSystemCode)) {
                                    conditionConfigJson = extSystemCode;
                                }
                            }
                        }
                    }
                }
                if (!KiteStringUtils.contains(conditionConfigJson, objId)) {
                    continue;
                }
                KitePageDefineDTO kitePageDefine = new KitePageDefineDTO();
                String appId = String.valueOf(pageTraceDTO.getAppId());
                if (KiteStringUtils.equals(appId, "-1")) {
                    //销售中心应用
                    kitePageDefine.setPageUrl(pageTraceDTO.getPagePath());
                    kitePageDefine.setProvincePageUrl("");
                }
                else {
                    isExist = false;
                    if (KiteStringUtils.equalsAny(tacheCode, null, "", KeyConsts3.ORDER_INPUT)) {
                        kitePageDefine.setPageUrl("/kiteSecDev");
                    }
                    else {
                        if (pageTraceDTO.getPageVersionId() == null) {
                            kitePageDefine.setPageUrl("");
                        }
                        else {
                            kitePageDefine.setPageUrl("/kiteSecDevOrder");
                        }
                    }
                    String provincePageUrl = getProvincePageUrl(pageTraceDTO);
                    kitePageDefine.setProvincePageUrl(provincePageUrl);
                }
                kitePageDefine.setDefineId(String.valueOf(pageTraceDTO.getTraceId()));
                kitePageDefine.setName(pageTraceDTO.getTraceName());
                kitePageDefine.setRemark(pageTraceDTO.getRemark());
                kitePageDefine.setApplyRegionCode("");
                kitePageDefine.setStatusCd(CoreDataPublic.PUB_C_0001_1000);
                kitePageDefines.add(kitePageDefine);
            }
            if (isExist) {
                return null;
            }
            pageNavigationDTO.setPageDefineList(kitePageDefines);
        }

        return pageNavigationDTO;
    }

    /**
     * 获取省份页面路径
     *
     * @param pageTraceDTO pageTraceDTO
     * @return 页面路径
     */
    private String getProvincePageUrl(PageTraceDTO pageTraceDTO) {
        Long appId = pageTraceDTO.getAppId();
        Long pageVersionId = pageTraceDTO.getPageVersionId();
        //获取当前环境
        String busiAreaType = "";
        String type = DcSystemParamCache.getDcParamVal(KeyConsts.DC_SYSTEM_PARAM_ENV_TYPE);
        if (KiteStringUtils.equals(type, KeyConsts.TEST)) {
            // 测试环境
            busiAreaType = "test";
        }
        else if (KiteStringUtils.equals(type, KeyConsts.PROD)) {
            // 生产环境
            busiAreaType = "product";
        }else if (KiteStringUtils.equals(type, KeyConsts.DEV)) {
            // 开发环境
            busiAreaType = "develop";
        }else if (KiteStringUtils.equals(type, "uat")) {
            // 准生产
            busiAreaType = "preProduct";
        }
        List<String> pageUrlList = pageTraceMapper.selectPageUrl(appId, busiAreaType);
        if (KiteListUtils.isEmpty(pageUrlList)) {
            return null;
        }
        String pageUrl = pageUrlList.get(0) + "/#/kiteSecDev/";
        if (pageVersionId != null) {
            pageUrl = pageUrl + pageVersionId + "?appId=" + appId;
        }
        return pageUrl;
    }

    private List<PageTraceDTO> mergePageTraceDTO(List<PageTraceDTO> pageTraceList, List<PageTraceDTO> pageTraceListExt) {
        List<PageTraceDTO> finalPageTraceList = new ArrayList<>();
        pageTraceList.forEach(pageTraceDTO -> {
            Long traceId = pageTraceDTO.getTraceId();
            List<PageTraceDTO> pageTraceExt = pageTraceListExt.stream().filter(pageTrace -> pageTrace.getTraceId().equals(traceId)).collect(Collectors.toList());
            if (KiteListUtils.isEmpty(pageTraceExt)) {
                PageTraceDTO pageTraceFinal = new PageTraceDTO();
                pageTraceFinal.setTraceCode(pageTraceDTO.getTraceCode());
                pageTraceFinal.setTraceName(pageTraceDTO.getTraceName());
                pageTraceFinal.setRemark(pageTraceDTO.getRemark());
                pageTraceFinal.setSort(pageTraceDTO.getSort());
                pageTraceFinal.setTraceId(pageTraceDTO.getTraceId());
                pageTraceFinal.setAppId(pageTraceDTO.getAppId());
                pageTraceFinal.setPageVersionId(pageTraceDTO.getPageVersionId());
                pageTraceFinal.setConditionConfigJson(pageTraceDTO.getConditionConfigJson());
                pageTraceFinal.setPagePath(pageTraceDTO.getPagePath());
                finalPageTraceList.add(pageTraceFinal);
            }
            else {
                pageTraceExt.forEach(pageTrace -> {
                    PageTraceDTO pageTraceFinal = new PageTraceDTO();
                    pageTraceFinal.setTraceCode(pageTraceDTO.getTraceCode());
                    pageTraceFinal.setTraceName(pageTraceDTO.getTraceName());
                    pageTraceFinal.setRemark(pageTraceDTO.getRemark());
                    pageTraceFinal.setSort(pageTraceDTO.getSort());
                    pageTraceFinal.setTraceId(pageTraceDTO.getTraceId());
                    pageTraceFinal.setAppId(pageTrace.getAppId());
                    pageTraceFinal.setPageVersionId(pageTrace.getPageVersionId());
                    pageTraceFinal.setConditionConfigJson(pageTrace.getConditionConfigJson());
                    pageTraceFinal.setPagePath(pageTrace.getPagePath());
                    finalPageTraceList.add(pageTraceFinal);
                });
            }
        });
        return finalPageTraceList;
    }

    private BusiObject getValidBusiObject(String busiObjectCode) {
        BusiObject busiObject = null;
        Example example = new Example(BusiObject.class);
        example.createCriteria().andEqualTo("busiObjectCode", busiObjectCode)
            .andEqualTo("statusCd", "00A");

        BusiObjectMapper busiObjectMapper = SpringUtil.getBean(BusiObjectMapper.class);
        List<BusiObject> busiObjectList = busiObjectMapper.selectByExample(example);
        if (!KiteCartListUtils.isEmpty(busiObjectList)) {
            busiObject = busiObjectList.get(0);
        }
        return busiObject;
    }
}
